package com.maiji.cloud.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.maiji.cloud.entities.login.AppUser;
import com.maiji.cloud.request.BaseDataReqDto;
import com.maiji.cloud.request.login.*;
import com.maiji.cloud.response.BaseDataResDto;
import com.maiji.cloud.response.BaseOutPutDto;
import com.maiji.cloud.response.BaseResDto;
import com.maiji.cloud.response.Status;
import com.maiji.cloud.response.login.AppUserResData;
import com.maiji.cloud.service.AppUserService;
import com.maiji.cloud.utils.UUID_MD5;
import org.apache.commons.lang3.StringUtils;
import org.eclipse.jetty.util.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

@RestController
public class LoginController {
	private static final Logger logger = LoggerFactory.getLogger(LoginController.class);

    @Value("${maijiOfficialId}")
    private String maijiOfficialId;
    @Autowired
    private AppUserService appUserService;

    /**
     *  注册
     * @param baseDataReqDto
     * @return
     */
    @PostMapping("/checkLogon")
    public BaseResDto checkLogon (@RequestBody BaseDataReqDto<String> baseDataReqDto) {
        String tel = baseDataReqDto.getData();
        if (StringUtil.isBlank(tel) || ! tel.matches("^[1][0-9]{10}$")) return new BaseResDto(Status.PARAMETERERROR);
        return appUserService.checkLogon(tel);
    }

    /**
     *  注册
     * @param baseDataReqDto
     * @return
     */
    @PostMapping("/logon")
    public BaseDataResDto<String> logon (@RequestBody BaseDataReqDto<AppUserLogonReqData> baseDataReqDto) {
    	logger.info("LoginController.logon baseDataReqDto is {}", JSON.toJSON(baseDataReqDto));
        String tel = baseDataReqDto.getData().getTel();
        String code = baseDataReqDto.getData().getCode();
        String pwd = baseDataReqDto.getData().getPwd();
        String distributionNum = baseDataReqDto.getData().getDistributionNum();
        if (StringUtil.isBlank(tel) || StringUtil.isBlank(code) || StringUtil.isBlank(pwd))
            return new BaseDataResDto(Status.PARAMETERERROR);
        return appUserService.logon(tel, code, pwd, distributionNum);
    }

    /**
     *  登录：1-手机号密码登录，2-手机号验证码登录，3-第三方登录
     * @param baseDataReqDto
     * @return
     */
    @PostMapping("/login")
    public BaseDataResDto<String> login (@RequestBody BaseDataReqDto<AppUserLoginReqData> baseDataReqDto) {
    	logger.info("LoginController.logon BaseDataReqDto is {}",JSON.toJSON(baseDataReqDto));
        String tel = baseDataReqDto.getData().getTel();
        String pwd = baseDataReqDto.getData().getPwd();
        String code = baseDataReqDto.getData().getCode();
        String openId = baseDataReqDto.getData().getOpenId();
        String qqId = baseDataReqDto.getData().getQqId();
        String wbId = baseDataReqDto.getData().getWbId();
        String distributionNum = baseDataReqDto.getData().getDistributionNum();
        return appUserService.login(tel, pwd, code, openId, qqId, wbId, distributionNum);
    }

    /**
     *  退出登录
     * @param maijiToken
     * @return
     */
    @PostMapping("/logout")
    public BaseResDto logout (@RequestHeader("maijiToken") String maijiToken) {
        if (StringUtil.isBlank(maijiToken)) return new BaseResDto(Status.TOKENINVALID);
        return appUserService.logout(maijiToken);
    }

    /**
     *  第三方登录绑定手机号
     * @param baseDataReqDto
     * @return
     */
    @PostMapping("/bindTel")
    public BaseDataResDto<AppUserResData> bindTel (@RequestBody BaseDataReqDto<AppUserBindTelReqData> baseDataReqDto) {
    	logger.info("LoginController.logon baseDataReqDto is {}",JSON.toJSON(baseDataReqDto));
    	String tel = baseDataReqDto.getData().getTel();
        String code = baseDataReqDto.getData().getCode();
        String openId = baseDataReqDto.getData().getOpenId();
        String qqId = baseDataReqDto.getData().getQqId();
        String wbId = baseDataReqDto.getData().getWbId();
        String nickName = baseDataReqDto.getData().getNickName();
        String headUrl = baseDataReqDto.getData().getHeadUrl();
        String distributionNum = baseDataReqDto.getData().getDistributionNum();
        if (StringUtil.isBlank(tel) || !tel.matches("^[1][0-9]{10}$") || StringUtil.isBlank(code))
            return new BaseDataResDto(Status.PARAMETERERROR);
        return appUserService.bindTel(tel, code, openId, qqId, wbId, nickName, headUrl, distributionNum);
    }

    /**
     *  修改密码或忘记密码
     * @param baseDataReqDto
     * @return
     */
    @PostMapping("/updatePwd")
    public BaseDataResDto<String> updatePwd (@RequestBody BaseDataReqDto<AppUserUpdatePwdReqData> baseDataReqDto,
                                             @RequestHeader(name = "maijiToken", required = false) String maijiToken) {
    	logger.info("LoginController.logon baseDataReqDto is {}",JSON.toJSON(baseDataReqDto));
    	String tel = baseDataReqDto.getData().getTel();
        String code = baseDataReqDto.getData().getCode();
        String pwd = baseDataReqDto.getData().getPwd();
        String oldPwd = baseDataReqDto.getData().getOldPwd();
        if (StringUtil.isBlank(tel) && StringUtil.isBlank(maijiToken))
            return new BaseDataResDto(Status.PARAMETERERROR);
        if (StringUtil.isBlank(code) && StringUtil.isBlank(oldPwd))
            return new BaseDataResDto(Status.PARAMETERERROR);
        if (StringUtil.isBlank(pwd) || !pwd.matches("^(?=.*[a-zA-Z])(?=.*\\d)[a-zA-Z\\d]{6,}$"))
            return new BaseDataResDto(Status.PARAMETERERROR);
        return appUserService.updatePwd(maijiToken, tel, code, oldPwd, pwd);
    }

    /**
     *  修改注册手机号
     * @param baseDataReqDto
     * @return
     */
    @PostMapping("/updateTel")
    public BaseDataResDto<String> updateTel (@RequestBody BaseDataReqDto<AppUserUpdateTelReqData> baseDataReqDto,
                                             @RequestHeader("maijiToken") String maijiToken) {
    	logger.info("LoginController.logon baseDataReqDto is {}",JSON.toJSON(baseDataReqDto));
        String tel = baseDataReqDto.getData().getTel();
        String code = baseDataReqDto.getData().getCode();
        if (StringUtil.isBlank(tel) || ! tel.matches("^[1][0-9]{10}$") || StringUtil.isBlank(code))
            return new BaseDataResDto(Status.PARAMETERERROR);
        return appUserService.updateTel(tel, code, maijiToken);
    }

    /**
     * 获取麦吉官方App账号token
     * @return
     */
    @GetMapping("getMaijiAppOfficialToken")
    public BaseOutPutDto<String> getMaijiAppOfficialToken(){
        AppUser appUser = appUserService.selectById(maijiOfficialId);
        if (appUser == null) return new BaseOutPutDto(Status.ERROR);
        return new BaseOutPutDto<String>(Status.SUCCESS).setData(appUser.getToken());
    }
    
	/**
	 * 校验登录密码是否正确
	 * 
	 * @param param
	 * @param maijiToken
	 * @return
	 */
	@PostMapping("/checkLoginPassWord")
	public BaseDataResDto<Boolean> checkLoginPassWord(@RequestBody BaseDataReqDto<String> param,
			@RequestHeader("maijiToken") String maijiToken) {
		logger.info("LoginController.logon param is {}",JSON.toJSON(param));

		if (StringUtils.isBlank(param.getData()))
			return new BaseDataResDto<Boolean>(Status.PARAMETERERROR);
		EntityWrapper<AppUser> entityWrapper = new EntityWrapper<>();

		Boolean flag = false;
		entityWrapper.eq("token", maijiToken);
		AppUser appUser = appUserService.selectOne(entityWrapper);

		if (appUser.getPwd().equals(UUID_MD5.md5Str(param.getData())))
			flag = true;
		
		if(!flag)return new BaseDataResDto<Boolean>(Status.PWDOLDERROR,"密码错误").setData(flag);

		return new BaseDataResDto<Boolean>(Status.SUCCESS).setData(flag);

	}

	/**
	 * 注销账户
	 * @param maijiToken
	 * @return
	 */
	@PostMapping("/logoutAccount")
	public BaseResDto logoutAccount(@RequestBody BaseDataReqDto<String> param,@RequestHeader("maijiToken") String maijiToken){
		logger.info("LoginController.logon param is {}",JSON.toJSON(param));
		return appUserService.logoutAccount(param,maijiToken);
	}

    /**
     * 禁止用户登录
     * @param baseDataReqDto
     * @return
     */
    @PostMapping("/banAppUser")
	public BaseResDto banAppUser (@RequestBody BaseDataReqDto<AppUser> baseDataReqDto) {
        AppUser appUser = baseDataReqDto.getData();
        return appUserService.banAppUser (appUser);
    }

}
